import pyb
import time
from pyb import SPI
from pyb import Accel
from pyb import Pin
import hc_sr04
import hcsr04
import sh1106

for i in range(2):
    for l in range(4):
        led = pyb.LED(l+1)
        led.toggle()
        pyb.delay(350)

accel = Accel()
print(accel.x(), accel.y(), accel.z(), accel.tilt())

# hc-sr04

# sh1106
# pyb1.1 Pin Map SPI
#       - 3v - xxxxxx   - Vcc
#       - G  - xxxxxx   - Gnd
# x6    - D7 - GPIO 13  - Din / MOSI fixed
# x8    - D5 - GPIO 14  - Clk / SCLK fixed
# x1    - D8 - GPIO 4   - CS (optional, if the only connected device)
# x2    - D2 - GPIO 5   - D/C
# x3    - D1 - GPIO 2   - Res (required, unless a Hardware reset circuit is connected)
#
# for CS, D/C and Res other ports may be chosen.


def init_sh1106():
    spi = SPI(1, SPI.MASTER, baudrate=8000000, polarity=0, phase=0)

    cs = pyb.Pin.board.X1
    dc = pyb.Pin.board.X2
    res = pyb.Pin.board.X3

    display = sh1106.SH1106_SPI(128, 64, spi, dc, res, cs)
    display.sleep(False)
    display.fill(0)
    return display


def show_str(display, str, old_str, x, y):
    if old_str != None:
        display.text(old_str, x, y, 0)
        display.show()
    display.text(str, x, y, 1)
    display.show()


def scaning(display, is_scan):
    display.text('scaning...', 50, 0, 0)
    display.show()
    display.text('finish.', 50, 0, 0)
    display.show()
    if is_scan:
        display.text('scaning...', 50, 0, 1)
    else:
        display.text('finish.', 50, 0, 1)
    display.show()


before_value = None


def show_distance(value):
    global before_value
    if before_value != None:
        display.text(before_value, 0, 10, 0)
        display.show()

    display.text(value, 0, 10, 1)
    display.show()
    before_value = value


def test_sh1106():
    spi = SPI(1, SPI.MASTER, baudrate=8000000, polarity=0, phase=0)

    cs = pyb.Pin.board.X1
    dc = pyb.Pin.board.X2
    res = pyb.Pin.board.X3

    display = sh1106.SH1106_SPI(128, 64, spi, dc, res, cs)
    display.sleep(False)
    display.fill(0)
    display.text('Testing 1', 0, 0, 1)
    display.show()
    for i in range(0, 10):
        s = str(i)
        display.text(s, 0, 10, 1)
        display.show()
        time.sleep(2)
        display.text(s, 0, 10, 0)
        display.show()


# test_sh1106()

display = init_sh1106()
show_str(display, 'State:', None, 0, 0)

trig_pin = pyb.Pin('Y2', Pin.OUT)
echo_pin = pyb.Pin('Y1', Pin.IN)
trig_pin.low()
echo_pin.low()

t1=time.ticks_us()
time.sleep_us(2)
t2 = time.ticks_us()
print("ticks %d" % time.ticks_diff(t2, t1))


h = hcsr04.HCSR04(trig_pin, echo_pin)

print("distance %dmm" % h.distance_cm())

for i in range(0, 10):
    scaning(display, True)
    show_distance('?')
    d = hc_sr04.distance(trig_pin, echo_pin)
    ##d = h.distance_mm()
    scaning(display, False)
    show_distance(str(d)+'mm')
    time.sleep(5)
